#
# MakeFigures.R
#
# Replication file for
# Hill, Seth J. and Gregory A. Huber. 2018. ``On The Meaning of Survey Reports of Roll Call `Votes','' American Journal of Political Science.
#

rm(list=ls())
if (.Platform$OS == "windows") {
  # Set working directory in location of script.
  .doit <- function() { # only works with R.exe; trap errors if using Rscript.exe
  frame_files <- lapply(sys.frames(), function(x) x$ofile);frame_files <- Filter(Negate(is.null), frame_files)
  PATH <- dirname(frame_files[[length(frame_files)]]); setwd(PATH) ; rm(PATH,frame_files)
  }
  try(.doit(),silent=T)
}
library(bit64)
library(data.table)
options(stringsAsFactors=F)
library(RColorBrewer)
palette(brewer.pal(n=6,name="PiYG"))
par(cex.axis=1.2,cex.lab=1.2)

#
# %%%%%%%%%%%%%%%%%%%%%%%%
# Data outsheeted from 02_02_CCES2014_PerformCoreAnalysis.do
# %%%%%%%%%%%%%%%%%%%%%%%%
#
DT <- fread("Tables/SupportByBillTreatPid.csv")
DT <- DT[bill != "",]

#
# %%%%%%%%%%%%%%%%%%%%%%%%
# Comparison of information treatment to standard
# support and congressional vote by bill and party.
# %%%%%%%%%%%%%%%%%%%%%%%%
#

.slope <- function(x,y1,y2,pch=19,lab="D",col=2) {
  # Create a sloping line connecting two points.
  y1 <- unlist(y1)
  y2 <- unlist(y2)
  x0 <- x - 0.5
  x1 <- x + 0.5
  segments(x0=x0,x1=x1,y0=y1,y1=y2,lwd=2)
  points(x=c(x0,x1),y=c(y1,y2),pch=pch,col=col,cex=1.5)
  text(x1,y2,pos=4,labels=lab)
}

.slopeSupportPlot <- function(DT,min.count=31,lvar="No=0",rvar="Yes=1",tvar=NULL,labs=c("D","R"),member.votes=T) {
  # Make slope plot connecting support in two conditions.
  # Arguments.
  #  DT -- data.table of data.
  #  min.count -- minumum number in cell in order to plot.
  #  lvar -- variable measuring left hand support.
  #  rvar -- variable measuring right hand support.
  #  tvar -- variable with t ratio to display at y=-0.1.
  #  labs -- labels for two parties.
  #  member.votes -- plot MC vote support?
  par.old <- par(mar=c(4.1,3.1,3.6,1.1))
  palette(brewer.pal(n=6,name="Set1"))

  # Open plot.
  plot(x=c(1,DT[,length(unique(bill))]*3),y=c(0,1),type='n',ann=F,axes=F);axis(2,las=2)
  title(ylab="Proportion supporting bill",line=2.1)
  abline(h=0.5,col='gray')
  # Plot for each bill.
  x <- 1
  for (bl in DT[,sort(unique(bill))]) {
    # Dem slope.
    counts <- c(DT[bill == bl & treatment == lvar & pid3_DtoR == "Dem",n], DT[bill == bl & treatment == rvar & pid3_DtoR == "Dem",n])
    # only plot if above min.counts.
    if (all(counts >= min.count)) {
      .slope(x=x,y1=DT[bill == bl & treatment == lvar & pid3_DtoR == "Dem",vote_yea], y2=DT[bill == bl & treatment == rvar & pid3_DtoR == "Dem",vote_yea], lab=labs[1], col=2)
    }
    # Rep slope.
    counts <- c(DT[bill == bl & treatment == lvar & pid3_DtoR == "Rep",n], DT[bill == bl & treatment == rvar & pid3_DtoR == "Rep",n])
    # only plot if above min.counts.
    if (all(counts >= min.count)) {
      .slope(x=x,y1=DT[bill == bl & treatment == lvar & pid3_DtoR == "Rep",vote_yea], y2=DT[bill == bl & treatment == rvar & pid3_DtoR == "Rep",vote_yea], lab=labs[2], col=1, pch=15)
    }

    if (member.votes & rvar != "votec_split") {
      # Dem member votes.
      points(x=x+1.5,y=DT[bill == bl,dvotesfor][1]/100,col=2,pch=1,cex=1.5)
      # Rep member votes.
      points(x=x+1.5,y=DT[bill == bl,rvotesfor][1]/100,col=1,pch=0,cex=1.5)
    }
    if (!is.null(tvar)) {
      text(x=x+.5,y=0.05,labels=sprintf("t=%1.1f",DT[bill == bl & treatment == rvar,tvar,with=F][1,]),pos=1)
    }
    # Label x-axis.
    axis(ifelse(x%%2==0,1,3),at=x+.5,labels=paste(strwrap(bl,15),collapse="\n"),tick=F,cex.axis=.8,line=ifelse(x%%2==0,2,-1))
    abline(v=x+2,lty=2)
    x <- x+3
  }
  par(par.old)
}

# All info.
DT <- fread("Tables/SupportByBillTreatPid.csv")
DT <- DT[bill != "",]
pdf("Figures/Figure01InfoVsStndSupport.pdf",width=10,height=6)
.slopeSupportPlot(DT,tvar="did_t")
dev.off()

# All info unweighted.
DT <- fread("Tables/SupportByBillTreatPid-Unweighted.csv")
DT <- DT[bill != "",]
pdf("Figures/FigureA09InfoVsStndSupportUnweighted.pdf",width=10,height=6)
.slopeSupportPlot(DT,tvar="did_t")
dev.off()

# Cross pid-by-ideo.
DT <- fread("Tables/SupportByBillTreatPid-Cross-Ideo.csv")
DT <- DT[bill != "",]
pdf("Figures/FigureA03InfoVsStndSupport-Cross-Ideo.pdf",width=10,height=6)
par(mfrow=c(2,1))
# Matched ideo-pid.
# Aggregate across matched ideo3 by party
# (ie, aggreate together lib and mod Dems, and
# mod and con Reps).
DT2 <- DT[(ideo3 != "Conservative" & pid3_DtoR == "Dem") | (ideo3 != "Liberal" & pid3_DtoR == "Rep"), list(votes_yea=sum(vote_yea*n),n=sum(n)),by=c("bill","treatment","pid3_DtoR","dvotesfor","rvotesfor")]
DT2[,vote_yea := votes_yea/n]
.slopeSupportPlot(DT2, min.count=20)
# Note enough cases for mod.
#.slopeSupportPlot(DT[ideo3 == "Moderate/Not sure",],min.count=20)
# Mismatched ideo-pid.
.slopeSupportPlot(DT[(ideo3 == "Conservative" & pid3_DtoR == "Dem") | (ideo3 == "Liberal" & pid3_DtoR == "Rep"),], min.count=18)
dev.off()
